<template lang="html">
  <el-dialog
    title="添加人员"
    width="850px"
    :wrapperClosable="false"
    append-to-body
    destroy-on-close
    :visible="dialogVisible"
    @close="close"
  >
    <div class="draw-wrapper">
      <!-- 顶部搜索 -->
      <page-header
        v-if="dialogVisible"
        slot="header"
        ref="pageHeader"
        @doSearch="doSearch"
        @doReset="doReset"
      />

      <el-row v-loading="wrapperLoading">
        <el-col :span="12">
          <el-card shadow="never" class="mr10">
            <div class="mb10 title">可选角色列表</div>

            <!-- table -->
            <el-table
              ref="leftTable"
              v-loading="wrapperLoading"
              :data="leftTableData"
              tooltip-effect="dark"
              border
              stripe
              style="width: 100%"
              @select="handleLeftSelectionChange"
              @select-all="leftSelectAll"
            >
              <el-table-column type="selection" align="center" />
              <el-table-column
                label="角色名称"
                show-overflow-tooltip
                align="center"
                prop="roleName"
              />
              <el-table-column
                prop="areaFullName"
                label="地址"
                show-overflow-tooltip
                align="center"
              />
              <el-table-column
                prop="organizeName"
                label="部门"
                show-overflow-tooltip
                align="center"
              />
            </el-table>

            <!-- 底部分页 -->
            <footer-page
              class="mt10"
              layout="total, prev, pager, next"
              :pageSize="leftPageSize"
              :currentPage="leftCurrentPage"
              :total="leftTotal"
              :small="true"
              @handleCurrentChange="handleLeftCurrentChange"
            />
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card shadow="never" class="ml10">
            <div class="mb10">
              <span class="fb fz16">已选角色</span>
              <span class="pl10">已选{{ rightTotal }}个角色</span>
            </div>

            <!-- table -->
            <el-table
              ref="rightTable"
              v-loading="wrapperLoading"
              :data="rightTableData"
              tooltip-effect="dark"
              border
              style="width: 100%"
              max-height="440"
            >
              <el-table-column
                label="角色名称"
                show-overflow-tooltip
                align="center"
                prop="roleName"
              />
              <el-table-column
                label="地址"
                show-overflow-tooltip
                align="center"
                prop="areaFullName"
              />
              <el-table-column
                label="部门"
                show-overflow-tooltip
                align="center"
                prop="organizeName"
              />
              <el-table-column label="操作" align="center">
                <template slot-scope="{ row }">
                  <el-button type="text" @click="doDel(row)">移除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <!-- 底部分页 -->
            <footer-page
              class="mt10"
              layout="total, prev, pager, next"
              :pageSize="rightPageSize"
              :currentPage="rightCurrentPage"
              :total="rightTotal"
              :small="true"
              @handleCurrentChange="handleRightCurrentChange"
            />
          </el-card>
        </el-col>
      </el-row>

      <!-- 底部按钮 -->
      <div class="mt20" flex="dir:right">
        <el-button
          type="primary"
          :disabled="!rightTotalTableData.length"
          :loading="btnLoading"
          @click="doSubmit"
          >确认</el-button
        >
        <el-button class="mr10" @click="close">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import FooterPage from "components/footer-page";
import PageHeader from "./components/page-header";
import { UserRoleSave, UserRoleList } from "api/sys/user-role";
import { RolePowerList } from "api/sys/role";
import dialogMixin from "mixins/dialogMixin";

export default {
  components: {
    FooterPage,
    PageHeader,
  },
  mixins: [dialogMixin],
  props: {
    // 当前选择的用户id
    currentId: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 存储搜索栏中的数据
      searchObj: {},
      // 左侧table的数据
      leftTableData: [],
      // 一页多少条数据
      leftPageSize: 10,
      // 当前页码数
      leftCurrentPage: 1,
      // 左侧数据总量
      leftTotal: 0,
      // 右侧table中的数据
      rightTableData: [],
      // 右侧table中所有数据
      rightTotalTableData: [],
      // 一页多少条数据
      rightPageSize: 10,
      // 当前页码数
      rightCurrentPage: 1,
      // 面板的搜索
      wrapperLoading: false,
    };
  },
  computed: {
    // 左侧数据总量
    rightTotal() {
      return this.rightTotalTableData.length;
    },
  },

  methods: {
    /**
     * 初始化弹窗
     */
    initForm() {
      this.getDoubleTableData();
    },
    /**
     * 顶栏的搜索
     */
    doSearch(obj) {
      this.leftCurrentPage = 1;
      obj && (this.searchObj = obj);
      this.handleLeftCurrentChange();
    },
    /**
     * 重置
     */
    async doReset() {
      this.leftCurrentPage = 1;
      this.searchObj = {};
      await this.$nextTick();
      this.handleLeftCurrentChange();
    },
    /**
     * 左侧table选择
     */
    handleLeftSelectionChange(val) {
      // 左侧table没有选中的id集合
      let notSelectedIds = [];
      // 左侧table被选中的id集合
      let selectedIds = [];
      // 设置上面两值
      const allIdsArr = val.map((item) => item.id);
      this.leftTableData.map((item) => {
        if (!allIdsArr.includes(item.id)) {
          notSelectedIds.push(item.id);
        } else {
          selectedIds.push(item.id);
        }
      });
      // 数据合并
      let tempArr = [...val, ...this.rightTotalTableData];
      // 去掉没有选的
      tempArr = tempArr.filter((item) => !notSelectedIds.includes(item.id));
      // 去重
      tempArr = tempArr.reduce((prev, element) => {
        if (!prev.find((el) => el.id === element.id)) {
          prev.push(element);
        }
        return prev;
      }, []);
      this.rightTableDataFormat(tempArr);
    },
    leftSelectAll(val) {
      this.handleLeftSelectionChange(val);
    },
    /**
     * 左侧切换分页
     */
    async handleLeftCurrentChange() {
      const data = await this.getLeftTableData();
      this.leftTableDataFormat(data);
      await this.$nextTick();
      this.setLeftTableSelected();
    },
    /**
     * 右侧切换分页
     */
    handleRightCurrentChange(val) {
      this.rightCurrentPage = val;
      const len = this.rightPageSize * (val - 1);
      this.rightTableData = this.rightTotalTableData.slice(len, len + this.rightPageSize);
    },
    /**
     * 单纯获取左侧table的列表数据
     */
    async getLeftTableData() {
      try {
        const data = await RolePowerList({
          current: this.leftCurrentPage,
          size: this.leftPageSize,
          userId: this.currentId,
          ...this.$clearEmptyObjAttritube(this.searchObj),
          // ...(this.roleName && { roleName: this.roleName })
        });
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 单纯获取右侧table的列表数据
     */
    async getRightTableData() {
      try {
        const data = await UserRoleList({
          userId: this.currentId,
        });
        return data;
      } catch (e) {
        console.log(e);
      }
    },
    /**
     * 左侧table接口数据格式化
     */
    leftTableDataFormat(obj) {
      const { records, total } = obj;
      this.leftTableData = records;
      this.leftTotal = total;
    },
    /**
     * 右侧table接口数据格式化，切换到第一页数据
     */
    rightTableDataFormat(arr) {
      this.rightTotalTableData = arr;
      this.rightTableData = arr.slice(0, this.rightPageSize);
    },
    /**
     * 获取左侧、右侧table中的数据
     */
    async getDoubleTableData() {
      try {
        this.wrapperLoading = true;
        const [leftData, rightData] = await Promise.all([
          this.getLeftTableData(),
          this.getRightTableData(),
        ]);
        // 左侧table数据整理
        this.leftTableDataFormat(leftData);
        // 右侧table数据整理
        this.rightTableDataFormat(rightData);
        await this.$nextTick();
        // 设置左侧table数据的选中状态
        this.setLeftTableSelected();
      } catch (e) {
        console.log(e);
      } finally {
        this.wrapperLoading = false;
      }
    },
    /**
     * 设置左侧table数据的选择状态
     */
    setLeftTableSelected() {
      const ids = this.rightTotalTableData.map((item) => item.id);
      this.leftTableData.map((item) => {
        if (ids.includes(item.id)) {
          this.$refs.leftTable.toggleRowSelection(item);
        }
      });
    },
    /**
     * 提交数据
     */
    async doSubmit() {
      try {
        this.btnLoading = true;
        await UserRoleSave({
          userId: this.currentId,
          roleIdList: this.rightTotalTableData.map((item) => item.id),
        });
        this.$message.success("角色权限分配成功");
        this.$emit("success");
        this.close();
      } catch (e) {
        console.log(e);
      } finally {
        this.btnLoading = false;
      }
    },
    /**
     * 右侧删除事件
     */
    async doDel({ id }) {
      let tempArr = [];
      this.rightTotalTableData.map((item) => {
        if (item.id === id) {
          this.leftTableData.map((childItem) => {
            if (childItem.id === id) {
              this.$refs.leftTable.toggleRowSelection(childItem);
            }
          });
        } else {
          tempArr.push(item);
        }
      });
      this.rightTotalTableData = tempArr;
      if (this.rightTableData.length === 1) {
        if (this.rightTotalTableData.length <= this.rightPageSize) {
          this.rightCurrentPage = 1;
        } else {
          this.rightCurrentPage -= 1;
        }
      }
      this.handleRightCurrentChange(this.rightCurrentPage);
    },
  },
};
</script>

<style lang="scss" scoped>
.top-search {
  width: 300px !important;
}
</style>
